<?php

namespace backend\grid;

use backend\assets\plugins\SwitcherAsset;
use common\libs\Constants;
use yii\helpers\Html;
use yii\helpers\Url;
use yii\web\View;

class SwitcherColumn extends DataColumn
{
    public $reload = '0';

    public $route = ['switcher'];

    public $formName = '';

    /**
     * {@inheritdoc}
     */
    protected function renderDataCellContent($model, $key, $index)
    {
        $params = is_array($key) ? $key : ['id' => (string)$key];
        $value  = $this->getDataCellValue($model, $key, $index);
        if (is_string($value) && !in_array($value, [0, '0', 1, '1', true, 'true', false, 'false'], true)) {
            $result = $value;
        } else {
            $params[$this->attribute] = empty($value) ? '1' : '0'; //反转
            $this->registerClientScript();
            $result = Html::checkbox(
                $this->attribute,
                Constants::YesNo_Yes == $value,
                [
                    'class'         => 'js-switch',
//                'data-method' => 'post',//加上这个导致页面发生跳转
                    'data-pjax'     => true,
                    'data-url'      => Url::to(['update', 'id' => $model['id']]),
                    'data-params'   => [$this->formName => $params],
                    'data-reload'   => $this->reload,
                    'data-toggle'   => 'switcher',
                    'switcher-size' => 'small',
                ]
            );
        }

        return $result;
    }

    public function registerClientScript()
    {
        SwitcherAsset::register($this->grid->view);
        $js = <<< JS
            $(function () {
                var elems = Array.prototype.slice.call(document.querySelectorAll('[data-toggle=switcher]'));
                elems.forEach(function (html) {
                    var disabled = !!$(html).data('switcher-disabled');
                    var size = $(html).data('switcher-size') || 'small';
                    var switchery = new Switchery(html, {size: size, disabled: disabled, disabledOpacity: 0.5});
                    $(html).data('switchery', switchery);
                });
            });
            $('.js-switch').on('change', function(){
                var switchery =  $(this).data("switchery");
                var url =  $(this).data("url");
                var reload =  $(this).data("reload");
                var checked =  $(this).is(':checked') ? '1' : '0';
                var data = $(this).data("params");

                $.ajax({
                    "url": url,
                    "data":data,
                    "dataType": "json",
                    "type": 'post',
                    'beforeSend': function () {
                        layer.load(2, {
                            shade: [0.1, '#fff'] //0.1透明度的白色背景
                        });
                    },
                    "success": function (data) {
                        layer.msg(data.message,{time:400});
                        // setSwitchery(switchery,data.status);
                        if(reload){
                            location.reload();
                        }
                    },
                    "error": function (jqXHR, textStatus, errorThrown) {
                        alert(jqXHR.responseJSON.message);
                    },
                    "complete": function () {
                        layer.closeAll('loading');
                    }
                });
            });

          /*
         * 切换Switchery开关函数
         * * switchElement Switchery对象
         * * checkedBool 选中的状态
         */
        function setSwitchery(switchElement, checkedBool) {
            if ((checkedBool && !switchElement.isChecked()) || (!checkedBool && switchElement.isChecked())) {
                switchElement.setPosition(true);
                switchElement.handleOnchange(true);
            }
        }
JS;
        $this->grid->view->registerJs($js, View::POS_READY); //因为可能会被pjax加载所以放在这里
    }
}
